package messaage;


import java.util.ArrayList;
import java.util.List;
import utils.LogHelper;
import forum.Thread;

/**
 * @author Olga
 * 
 */
public class GotTopicsOfForumMsg extends Message {
	protected String topicsOfForum;
	protected List<forum.Thread> topics;
	protected String forumID;

	/**
	 * 
	 */
	public GotTopicsOfForumMsg(String msg) {
		this.topicsOfForum = msg;
		this.topics = new ArrayList<forum.Thread>();
		this.parse(msg);
	}

	private void parse(String msg) {
		String[] splittedRoots = msg.split("ThreadNode:\nPostNode:\n");
		String[] splittedfields;
		Thread threadToAdd;
		this.forumID = splittedRoots[0].split("\n")[2];
		System.out.println("this.forumID: "+this.forumID);

		// create threads list
		for (int i = 1; i < splittedRoots.length; i++) {
			// create a new thread
			splittedfields = splittedRoots[i].split("\n");

			// take postID
			int postID = Integer.parseInt(splittedfields[0]);

			// take author
			String author = splittedfields[1];

			// take date
			String dateString = splittedfields[2];

			// take parent post ID. here must returned -1. thus not used
			//int parentID = Integer.parseInt(splittedfields[3]);

			// take subject
			String subject = splittedfields[4];

			// take content
			String content = "";
			for (int j = 5; j < splittedfields.length; j++) {
				if (j == splittedfields.length - 1)
					content += splittedfields[j];
				else
					content += splittedfields[j] + "\n";
			}

			// build thread
			threadToAdd = new Thread(postID, subject, content, author);

			// set date to published date
			String date;
			try {
				date = dateString;
				threadToAdd.getRoot().setDate(date);
			} catch (Exception e) {
				LogHelper.instance().log(
						"Date parsing failed in parsing GotTopicsOfForumMsg");
			}
		
			
			
			// add thread to list
			this.topics.add(threadToAdd);
		} // for
		
	} // parse

	@Override
	public String toString() {
		return "GotTopicsOfForum\n" + this.topicsOfForum + "\0";
	}

	/**
	 * @return the topicsOfForum
	 */
	public String getTopicsOfForum() {
		return topicsOfForum;
	}

	public List<Thread> getListOfTopics() {
		return this.topics;
	}

	public int getForumID() {
		return Integer.parseInt(this.forumID);
	}
}
